<?php

namespace app\admin\controller\lease;

use app\common\controller\Backend;

/**
 * 租赁订单管理
 *
 * @icon fa fa-user
 */
class Lease extends Backend
{

    protected $model = null;
    protected $expressqueryModel = null;
    protected $relationSearch = true;
    protected $BusinessModel = null;
    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Lease');
        $this->BusinessModel = model('Business.Business');
        $this->expressqueryModel = model('Expressquery');
        $status = [
            '1' => '已下单',
            '2' => '已发货',
            '3' => '租用中',
            '4' => '已归还',
            '5' => '未评价',
            '6' => '已完成',
        ];
        $this->view->assign('status', $status);
    }

    /**
     * 查看
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->with(['business', 'product'])
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with(['business', 'product'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
    // 订单详情
    public function detail($ids = null)
    {
        $row = $this->model->with(['business', 'review', 'provinces', 'citys', 'districts', 'product'])->find($ids);
        $this->assign('row', $row);
        return $this->view->fetch();
    }
    // 发货
    public function deliver($ids = null)
    {
        $expressquery = $this->expressqueryModel->all();
        $data = [];
        foreach ($expressquery as $item) {
            $data[$item['id']] = $item['name'];
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $params['id'] = $ids;
            $params['status'] = 2;
            // 定义验证器
            $validate = [
                [
                    'expid' => 'require',
                    'expcode' => 'require|unique:lease'
                ],
                [
                    'expid.require' => '配送物流未知',
                    'expcode.unique' => '配送物流单号已存在，请重新输入',
                    'expcode.require' => '请输入配送物流单号'
                ]
            ];
            $result = $this->model->validate(...$validate)->isUpdate(true)->save($params);
            if ($result === false) {
                $this->error($this->model->getError());
            } else {
                $this->success('发货成功');
            }
        }

        $this->assign('expressquery', $data);
        return $this->view->fetch();
    }
    // 退押金
    public function rent($ids = null)
    {
        $row = $this->model->find($ids);
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $data = ['id' => $ids, 'status' => '5', 'adminid' => $this->auth->id];

            if (!$row) {
                $this->error('订单不存在');
            }
            $addmoney = 0;
            if ($params['refund'] == 0) {
                $argument = trim($params['argument']);
                if ($argument == '' && empty($argument)) {
                    $this->error('扣押金理由必须填写');
                }
                if ($params['deduct'] == '' && empty($params['deduct'])) {
                    $this->error('扣除押金必须填写');
                }
                $deduct = floatval($params['deduct']);
                if ($deduct <= 0) {
                    $this->error('扣除押金必须大于0');
                }
                $addmoney = bcsub($row['rent'], $deduct, 2);
                if ($addmoney < 0) {
                    $this->error('扣除押金不能大于' . $row['rent']);
                }
                $data['deduct'] = $deduct;
                $data['argument'] = $params['argument'];
            } else {
                $deduct = floatval($row['rent']);
                $addmoney = $deduct;
            }
            $businfo = $this->BusinessModel->find($row['busid']);
            if (!$businfo) {
                $this->error('客户不存在');
            }
            $money = bcadd($businfo['money'], $addmoney, 2);
            $this->BusinessModel->startTrans();
            $this->model->startTrans();
            $res = $this->BusinessModel->isUpdate()->save(['id' => $businfo['id'], 'money' => $money]);
            if ($res === false) {
                $this->error($this->BusinessModel->getError());
            }
            $result = $this->model->isUpdate()->save($data);
            if ($result === false) {
                $this->BusinessModel->rollback();
                $this->error($this->model->getError());
            }
            $this->BusinessModel->commit();
            $this->model->commit();
            $this->success("退款成功");
        }
        $this->assign('row', $row);
        return $this->view->fetch();
    }
    /**
     * 软删除
     */
    public function del($ids = null)
    {
        $categoryList = $this->model->all($ids);
        if (empty($categoryList)) {
            $this->error('当前订单不存在');
        }
        $result = $this->model->destroy($ids);
        if (!$result) {
            $this->error($this->model->getError());
        }
        $this->success();
    }
}
